import wxValidate from 'wechat-validate'
Page({
  data: {
    countDownVisible: false,
    mobile:"",
    code:""
  },
   // 将插件注入到页面实例中
   behaviors: [wxValidate],
   rules: {
     mobile: [
       {required: true, message: '请填写手机号码!'},
       {pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!'}
     ],
     code:[
      {required: true, message: '请填写验证码!'},
      {pattern: /^\d{6}$/, message: '请填写正确的验证码!'}
     ]
   }, 
   // 倒计时组件事件
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  onLoad(query) {

    // 这个挂载在当前全局this上
    this.query = query;
  },
  // 获取验证码
  async getCode() {
    const {valid,message} = this.validate("mobile")
    if (valid) {
    
     // 调用接口获取验证码
     const res = await wx.http.get("/code",{mobile:this.data.mobile})
      // 点击后启用倒计时组件
      this.setData({countDownVisible: true})
      console.log(res);
  
    }else {
      wx.utils.toast(message)
    }
  },
  // 登陆确认
  async submitForm() {
    const {valid} = this.validate("mobile","code")
    if(valid) {
        // 调用登录接口
     const res  = await wx.http.post('/login', {
        mobile: this.data.mobile,
        code: this.data.code
      })
      console.log(res);
      
      const app = getApp();
      app.setToken('token',res.data.token);
      app.setToken('refreshToken',res.data.refreshToken)
      // 登陆成功后重定向到刚刚访问的页面
      wx.redirectTo({
        url:this.query.redirectUrl || '/pages/index/index'
      })
    }
  }
  
})
